import { defineStore } from "pinia";
import { reactive, watch } from "vue";

let shopCartStore = defineStore('shopCart', () => {
  let shopCartList = reactive([])
  if (localStorage.getItem('shopCartList')) {
    let keepList = JSON.parse(localStorage.getItem('shopCartList'))
    keepList.forEach(item => {
      shopCartList.push(item)
    })
  }
  watch(shopCartList, (newVal) => {
    localStorage.setItem('shopCartList', JSON.stringify(newVal))
  }, { deep: true })

  function addShopCart(item) {
    if (shopCartList.length === 0) {
      item.count = 1
      shopCartList.push(item)
    } else {
      let index = shopCartList.findIndex(e => e.id === item.id)
      if (index > -1) {
        shopCartList[index].count += 1
      } else {
        item.count = 1
        shopCartList.push(item)
      }
    }
  }
  function removeShopCartItem(list) {
    list.forEach((item) => {
      let index = shopCartList.indexOf(item)
      if (index > -1) {
        shopCartList.splice(index, 1)
      }
    })
  }
  function removeShopCart(item) {
    let index = shopCartList.indexOf(item)
    if (index > -1) {
      if (item.count > 1) {
        item.count--
      } else {
        shopCartList.splice(index, 1)
      }
    }
  }
  return {
    shopCartList,
    addShopCart,
    removeShopCart,
    removeShopCartItem
  }
})

export default shopCartStore